<template>
  <div class="keyClasp">
    <div>
      <ele-page
        v-loading="loading"
        :formConfig="searchConfig"
        ref="eleTable"
        :operateList="operateList"
        @handleOperateEvent="handleOperateEvent"
        :column="column"
        :getList="getList"
        uniqueId="mesProcessTable"
      >
      </ele-page>
    </div>
    <ele-form-drawer
      class="dialog-pack"
      :isLoading="isLoading"
      v-model="formDataDialog"
      v-bind="formDescDialog"
      :request-fn="handleSubmit"
      :visible.sync="visible"
      :title="title"
    >
    </ele-form-drawer>
    <el-image-viewer
      v-if="showViewer"
      :on-close="closeViewer"
      :url-list="showViewerImages"
      :initialIndex="initialIndex"
    />
  </div>
</template>

<script>
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
import { operateList, searchConfig, rowConfig, formDescDialogMinxin, formDescDialogCell } from './config'
import {
  getList,
  rowCreate,
  rowUpdate,
  rowPrint,
  rowDel,
  rowDetail,
  getPrintTypeList,
  addProcessCell
} from "@/api/cabinet/cabinetPrint/index"
import url from '@/axios/url'
import { HanYinPrint } from './print'
const { minioUrl } = url()
const hanYinTarget = window.proxy || window
// import printJS from "print-js";
export default {
  name: 'mesProcess',
  mixins: [formDescDialogMinxin, searchConfig, operateList, HanYinPrint],
  components: {
    ElImageViewer
  },
  data() {
    return {
      processCodeList: [],
      title: null,
      visible: false,
      isLoading: false,
      loading: false,
      formDataDialog: {},
      // operateList,
      getList,

      visibleCell: false, // 分配工位弹框
      isLoadingCell: false, // 分配工位弹窗loading
      // formDescDialogCell, // 分配工位表单配置
      formDataDialogCell: {}, // 分配工位数据对象
      addProcessCell, // 给现象分配原因
      // 列表页字段的绑定配置
      column: [
        {
          type: 'selection',
          fixed: 'left'
        },
        {
          type: 'index',
          label: $i18n.t('common.order'),
          width: 60,
          fixed: 'left'
        },
        {
          prop: 'vinCode',
          label: '车辆VIN码',
          minWidth: 160,
          showOverflowTooltip: true
        },
        {
          prop: 'uwbShortCode',
          label: 'UWB(短码)',
          minWidth: 160,
          showOverflowTooltip: true
        },
        {
          prop: 'uwbLongCode',
          label: 'UWB(长码)',
          minWidth: 160,
          showOverflowTooltip: true
        },
        {
          prop: 'printTime',
          label: '打码时间',
          minWidth: 160,
          showOverflowTooltip: true
        },
        {
          prop: 'printTypeCode',
          label: '打码类型',
          minWidth: 160,
          showOverflowTooltip: true,
          optionProp: {
            value: 'value',
            label: 'description'
          },
          option: async data => {
            const list = await getPrintTypeList()
            return list.data.result
          }
        },
        {
          prop: 'printTimes',
          label: '打码次数',
          minWidth: 160,
          showOverflowTooltip: true
        },
        {
          prop: 'sampleImage',
          label: '样例图片',
          minWidth: 160,
          showOverflowTooltip: true,
          render: (h, scope) => {
            let _dom = []
            if (scope.row.sampleImage) {
              _dom.push(
                <el-link
                  type="primary"
                  onClick={() => {
                    this.showImgViewer(scope.row)
                  }}
                >
                  {$i18n.t('common.view')}
                </el-link>
              )
            } else {
              _dom.push(<span>-</span>)
            }
            return _dom
          }
        },
        // {
        //   prop: 'processTypeId',
        //   label: $i18n.t('cabinet.cabinetName'),
        //   minWidth: 160,
        //   showOverflowTooltip: true
        // },
        // {
        //   prop: 'processProperty',
        //   label: $i18n.t('cabinet.cabinetCode'),
        //   minWidth: 140,
        //   showOverflowTooltip: true,
        //   optionProp: {
        //     value: 'value',
        //     label: 'description'
        //   },
        //   option: async data => {
        //     const list = await getProcessPropertyList()
        //     return list.data.result
        //   }
        // },
        // {
        //   prop: 'processCode',
        //   label: $i18n.t('cabinet.address'),
        //   minWidth: 160,
        //   showOverflowTooltip: true
        // },
        // {
        //   prop: 'processName',
        //   label: $i18n.t('cabinet.cabinetArea'),
        //   minWidth: 180,
        //   showOverflowTooltip: true
        // },
        // {
        //   prop: 'processProperty2',
        //   label: $i18n.t('cabinet.cabinetType'),
        //   minWidth: 140,
        //   showOverflowTooltip: true,
        //   optionProp: {
        //     value: 'value',
        //     label: 'description'
        //   },
        //   option: async data => {
        //     const list = await getProcessPropertyList()
        //     return list.data.result
        //   }
        // },
        // {
        //   prop: 'isReportStart',
        //   label: $i18n.t('common.remark'),
        //   minWidth: 220,
        //   showOverflowTooltip: true,
        //   require: true,
        //   optionProp: {
        //     value: 'value',
        //     label: 'description'
        //   },
        //   option: async data => {
        //     const list = await getYesOrNotList()
        //     return list.data.result
        //   }
        // },
        {
          prop: 'operate',
          label: '操作',
          width: 220,
          fixed: 'right',
          render: (h, scope) => {
            return <ele-row-operation scope={scope} rowConfig={rowConfig} onRowOperate={this.rowOperate} />
          }
        }
      ],
      showViewer: false,
      initialIndex: 0,
      showViewerImages: [
        'https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg',
        'https://fuss10.elemecdn.com/9/bb/e27858e973f5d7d3904835f46abbdjpeg.jpeg'
      ]
    }
  },
  computed: {},
  methods: {
    // 子应用中
    loadScript (url) {
      let script = document.createElement('script')
      script.setAttribute('type', 'text/javascript')
      script.setAttribute('src', url)
      let head = document.getElementsByTagName('head')
      if (head.length) {
        head[0].appendChild(script)
      } else {
        document.documentElement.appendChild(script)
      }
    },
    //图片预览展示
    showImgViewer(row) {
      this.showViewer = true
      this.showViewerImages = row.sampleImage ? [row.sampleImage] : []
    },
    //关闭图片预览弹框
    closeViewer() {
      this.showViewer = false
      this.initialIndex = 0
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.iddss === 1) {
        return 'warning-row'
      } else {
        return 'success-row'
      }
    },
    // 表格顶部按钮操作事件
    handleOperateEvent(data) {
      this.title = data.name
      const fnc = {
        export: () => {
          this.$confirm($i18n.t('keyClasp.exportPrompt'), $i18n.t('common.tip'), {
            confirmButtonText: $i18n.t('common.ok'),
            cancelButtonText: $i18n.t('common.cancel'),
            type: 'warning'
          }).then(() => {
            // const params = { ...this.getSearchParams(), ...this.otherParams }
            // exportExcel(data.url, params)
          })
        },
        add: () => {
          this.disableFields(false)
          this.formDataDialog = {}
          this.visible = true
        },
        deleteBatch: () => {
          this.$confirm($i18n.t('common.deleteBatch', { name: $i18n.t('mesProcess.name') }), $i18n.t('common.tip'), {
            confirmButtonText: $i18n.t('common.ok'),
            cancelButtonText: $i18n.t('common.cancel'),
            type: 'warning'
          }).then(() => {
            const ids = data.rows.map(val => val.id).join(',')
            this.rowDel(ids)
          })
        },
        exportExcel: () => {
          var url = `${minioUrl}/mes-template/标准工序模板.xls`
          window.open(url)
        }
      }
      fnc[data.handleName]()
    },
    // 网络图片url转base64
    convertImageUrlToBase64(imageUrl) {
      fetch(imageUrl)
        .then(response => response.blob())  
        .then(blob => {
          return new Promise((resolve, reject) => {  
            const reader = new FileReader();  
            reader.onloadend = () => resolve(reader.result);  
            reader.onerror = error => reject(error);  
            reader.readAsDataURL(blob);  
          });  
        })  
        .then(base64Data => { 
          // 使用箭头函数确保 this 指向 Vue 实例  
          console.log(base64Data) // 现在可以正确地将 base64Data 赋值给 this.imgSrc  
        })  
        .catch(error => {
          console.error('无法将图片 URL 转换为 Base64:', error);  
        })
        
    },
    // print(request) {
    //   var ip = '127.0.0.1'
    //   var port = '9099'
    //   var model = 'XT330' || 'HT300'
    //   var timeout = 3000;
    //   var interfacePort = 'NET'
    //   var tag = '10.182.54.42'
    //   var tag_port = '9100'
    //   var printer = new hanYinTarget.ZPL_JSSDK.Printer(ip, model, timeout, port, interfacePort, tag, tag_port);
    //   printer.print();

    // },
    convertImgToBase64(url, callback, outputFormat){
      var canvas = document.createElement('CANVAS'),
          ctx = canvas.getContext('2d'),
          img = new Image;
      img.crossOrigin = 'Anonymous';
      img.onload = function(){
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img,0,0);
        var dataURL = canvas.toDataURL(outputFormat || 'image/jpeg');
        callback.call(this, dataURL);
        canvas = null;
      };
      img.src = url;
    },
    // jsonPrint(imgUrl) {
    //   printJS({
    //     printable: imgUrl,
    //     type: "image",
    //     imageStyle: "width:100%;height:100%; margin-bottom:0px;",
    //   });
    // },
    net_img_print (imageUrl, row){
        
				if(!imageUrl){
					alert("未返回打印条码图片!");
				} else {
          let that = this
          var builder = new hanYinTarget.ZPL_JSSDK.Builder();
          builder.ZPL_StartFormat();
          //设置了打印浓度
          let printWith, xposition
          if(row.printTypeCode == '3') {
            that.tagIp = '172.16.50.29'
            printWith = 1010
            xposition = 0
          } else {
            that.tagIp = '172.16.50.30'
            printWith = 376
            xposition = 0
          }
          console.log("current change：",this.tagIp)
          builder.ZPL_SetPrintDarkness(20);
          builder.ZPL_SetPrintWidth(printWith);
          
					var imageData = this.convertImgToBase64(imageUrl, function(base64Img){
            // console.log(base64Img)
						//转化后的base64
            // 打印机自己生成 二维码
            // if(row.printTypeCode == '30') {
            //   builder.ZPL_ScalableFontText( 600, 10, 'UWB', 0, 16, 16, row.uwbShortCode);
            //   builder.ZPL_QRCode(100, 100, 0, 2, 10, 'M', 'A', 'A',
            //   "https://cartechmomtest.cosmoplat.com/mes-app/pages/oneCarCode/customerScanning?vin=" + 
            //   row.uwbShortCode
            //   );
            // } 
            // USB模式打印图片
            // if(row.printTypeCode == '30') {
            //   that.jsonPrint(base64Img)
            // } else {
              builder.ZPL_PrintImageStream(xposition, 0, base64Img);
            // }
					  builder.ZPL_EndFormat();
            console.log(builder.getPrintData())
						that.print(builder.getPrintData());
						return false;
					});
				}
		},
    // 表格行操作事件
    rowOperate({ handleName, name, row }) {
      this.title = name
      const fnc = {
        edit: () => {
          this.disableFields(false)
          this.rowDetail(row.id)
          this.visible = true
        },
        print: () => {
          this.$confirm('此操作将发起打印，是否继续？', $i18n.t('common.tip'), {
            confirmButtonText: $i18n.t('common.ok'),
            cancelButtonText: $i18n.t('common.cancel'),
            type: 'warning'
          }).then(() => {
            // this.convertImageUrlToBase64(row.sampleImage)
            console.log(row)
            this.net_img_print(row.sampleImage, row)
            this.printReport(row.id)
          })
          
        },
        detail: () => {
          this.disableFields(true)
          this.rowDetail(row.id)
          this.visible = true
        },
        delete: () => {
          this.$confirm($i18n.t('common.deleteSingle', { name: $i18n.t('mesProcess.name') }), $i18n.t('common.tip'), {
            confirmButtonText: $i18n.t('common.ok'),
            cancelButtonText: $i18n.t('common.cancel'),
            type: 'warning'
          }).then(() => {
            this.rowDel(row.id)
          })
        },
        transfer: () => {
          this.$refs.transferDrawer.drawer = true
          // this.getWorkCellList(row.processCode, row.processName, row)
        }
      }
      fnc[handleName]()
    },
    doSubmit({ title, api, data }) {
      this.isLoading = true
      api(data)
        .then(res => {
          const message = res.data.message
          this.$message.success(message || title)
          this.visible = false
          this.refresh()
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    // 弹框提交事件
    handleSubmit(data) {
      if (this.isLoading) return // 判断状态
      const params = this.formDataDialog.id
        ? { title: $i18n.t('common.editSuccess'), api: rowUpdate, data }
        : { title: $i18n.t('common.addSuccess'), api: rowCreate, data }

      this.doSubmit(params)
    },
    // 删除
    rowDel(data) {
      this.loading = true
      rowDel(data)
        .then(res => {
          const message = res.data.message
          this.$message.success(message || $i18n.t('common.deleteSuccess'))
          this.refresh()
        })
        .finally(() => {
          this.loading = false
        })
    },
    disableFields(flag) {
      this.formDescDialog.disabled = flag
      this.formDescDialog.isShowSubmitBtn = !flag
    },
    rowDetail(id) {
      rowDetail(id).then(res => {
        this.formDataDialog = res.data.result
      })
    },
    // 刷新表格数据
    refresh(isReset = true) {
      this.$refs.eleTable.refresh(isReset)
    }
  },
  mounted () {
    // this.loadScript('https://cartechmomtest.cosmoplat.com/mom/component/mes/ZPL_JSSdk0.0.0.3.js?_custom-exclude_=MAIN') 
  }
}
</script>
<style scoped lang="scss">
.mesProcess {
  /deep/.el-transfer-panel {
    width: 40% !important;
  }
  .warning-row {
    background: oldlace;
  }
}
</style>
